﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using DataTransferObject;
using BusinessLogicLayer;
namespace Main.Controls
{
    public partial class XayDungBoDe : System.Web.UI.UserControl
    {
        private List<clsCauHoi> DanhSachCauHoi;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["Sort"] = null;
                if (Request.QueryString["ID"] != null)
                {
                    hidDanhSachTruoc.Value = Request.QueryString["ds"].ToString();
                    lnkBackCauHoiCon.Visible = true;
                    lblTieuDe.Text = "Danh sách câu hỏi con của câu hỏi có ID:"+Request.QueryString["ID"]+"";
                    KhoaControl(false);
                    CauHoiBLL CauHoiService = new CauHoiBLL();
                    DanhSachCauHoi = CauHoiService.LayDanhSachCauHoiCon(Convert.ToInt32(Request.QueryString["ID"]));
                    gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataBind();
                    gridDanhSachCauHoi.Columns[0].Visible = false;
                    Session["DanhSachCauHoiTemp"] = DanhSachCauHoi;
                    if(hidDanhSachTruoc.Value=="ThuocDe")
                        lnkThemCauHoiVaoDe.Text = "Thêm câu hỏi mới";
                    else 
                        lnkThemCauHoiVaoDe.Text = "Trở về";
                }
                else
                {
                    LoadBoDe();
                }
                BoDeBLL BoDeService = new BoDeBLL();
                ddlBoDe.DataTextField = "TenDe";
                ddlBoDe.DataValueField = "MaDe";
                ddlBoDe.DataSource = BoDeService.DanhSachBoDe();
                ddlBoDe.DataBind();
                LoadBoLoc();
            }
        }

        // Đưa Dữ liệu vào bộ lọc
        private void LoadBoLoc()
        {
            ChuyenMucBLL ChuyenMucService = new ChuyenMucBLL();
            KyNangBLL KyNangService = new KyNangBLL();
            MucDoBLL MucDoService = new MucDoBLL();

            List<clsChuyenMuc> DanhSachChuyenMuc = ChuyenMucService.LayDanhSachChuyenMuc();
            DanhSachChuyenMuc.Insert(0, new clsChuyenMuc(-1, "--Chọn chuyên mục--", ""));
            DanhSachChuyenMuc.Insert(1, new clsChuyenMuc(0, "--Tất cả--", ""));
            ddlChuyenMuc.DataSource = DanhSachChuyenMuc;
            ddlChuyenMuc.DataTextField = "TenChuyenMuc";
            ddlChuyenMuc.DataValueField = "MaChuyenMuc";
            ddlChuyenMuc.DataBind();

            List<clsMucDo> DanhSachMucDo = MucDoService.DanhSachDoKho();
            DanhSachMucDo.Insert(0, new clsMucDo(-1, "--Chọn mức độ--"));
            DanhSachMucDo.Insert(1, new clsMucDo(0, "--Tất cả--"));
            ddlMucDo.DataSource = DanhSachMucDo;
            ddlMucDo.DataTextField = "TenMucDo";
            ddlMucDo.DataValueField = "MaMucDo";
            ddlMucDo.DataBind();

            List<clsKyNang> DanhSachKyNang = KyNangService.DanhSachKyNang();
            DanhSachKyNang.Insert(0, new clsKyNang(-1, "--Chọn kỹ năng--"));
            DanhSachKyNang.Insert(1, new clsKyNang(0, "--Tất cả--"));
            ddlKyNang.DataSource = DanhSachKyNang;
            ddlKyNang.DataTextField = "TenKyNang";
            ddlKyNang.DataValueField = "MaKyNang";
            ddlKyNang.DataBind();

            Common cm = new Common();
            Dictionary<string, int> LoaiCauHoi = cm.LoaiCauHoi();
            LoaiCauHoi.Remove("Câu hỏi con");
            ddlLoaiCauHoi.DataTextField = "key";
            ddlLoaiCauHoi.DataValueField = "value";
            ddlLoaiCauHoi.DataSource = LoaiCauHoi;
            ddlLoaiCauHoi.DataBind();
           
        }
        #region Phần Quản Lý Đề Thi
        // Phần Quản Lý Đề
        protected void gridDanhSachDe_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int mabode = Convert.ToInt32((gridDanhSachDe.Rows[e.RowIndex].FindControl("lblMaBoDe") as Label).Text);
                BoDeBLL BoDeService = new BoDeBLL();
                BoDeService.XoaBoDe(mabode);
                Notice.Visible = true;
                Notice.InnerText = "Đã xóa.";
                Errors.Visible = false;
                ScriptManager1.SetFocus(gridDanhSachDe);
                LoadBoDe();
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
                ScriptManager1.SetFocus(Errors);
            }
          
        }

        protected void gridDanhSachDe_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridDanhSachDe.EditIndex = e.NewEditIndex;
            gridDanhSachDe.DataSource = Session["DanhSachDe"] as List<clsBoDe>;
            gridDanhSachDe.DataBind();
            TextBox txtTen = gridDanhSachDe.Rows[gridDanhSachDe.EditIndex].FindControl("txtTenBoDe") as TextBox;
            DropDownList drop = gridDanhSachDe.Rows[gridDanhSachDe.EditIndex].FindControl("dropChuyenMuc") as DropDownList;
            LinkButton lnk = gridDanhSachDe.Rows[gridDanhSachDe.EditIndex].FindControl("lnkSave") as LinkButton;
            lnk.Attributes.Add("onclick", "return Check('" + txtTen.ClientID + "','" + drop.ClientID + "');");
        }

        protected void gridDanhSachDe_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                int mabode = Convert.ToInt32((gridDanhSachDe.Rows[e.RowIndex].FindControl("lblMaBoDe") as Label).Text);
                string tenbode = (gridDanhSachDe.Rows[e.RowIndex].FindControl("txtTenBoDe") as TextBox).Text;
                int machuyenmuc = Convert.ToInt32((gridDanhSachDe.Rows[e.RowIndex].FindControl("dropChuyenMuc") as DropDownList).SelectedValue);
                string mota = (gridDanhSachDe.Rows[e.RowIndex].FindControl("txtMoTa") as TextBox).Text;
                clsBoDe BoDe = new clsBoDe(mabode, tenbode, machuyenmuc, mota);
                BoDeBLL BoDeService = new BoDeBLL();
                BoDeService.SuaBoDe(BoDe);
                gridDanhSachDe.EditIndex = -1;
                Notice.Visible = true;
                Notice.InnerText = "Cập nhật thành công";
                Errors.Visible = false;
                ScriptManager1.SetFocus(gridDanhSachDe);               
                LoadBoDe();
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
            }
         
        }

        protected void gridDanhSachDe_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridDanhSachDe.PageIndex = e.NewPageIndex;
            if (Session["DanhSachDe"] != null)
            {
                gridDanhSachDe.DataSource = (Session["DanhSachDe"] as List<clsBoDe>);
                gridDanhSachDe.DataBind();
            }
            else
            {
                LoadBoDe();
            }
            System.Threading.Thread.Sleep(5000);
        }


        protected void gridDanhSachDe_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridDanhSachDe.EditIndex = -1;
            LoadBoDe();
            
        }

        protected void ddlBoDe_SelectedIndexChanged(object sender, EventArgs e)
        {
            BoDeBLL BoDeService = new BoDeBLL();
            List<clsCauHoi> DanhSachCauHoi = BoDeService.LayDanhSachCauHoiThuocBoDe(Convert.ToInt32(ddlBoDe.SelectedValue),1);
            if (DanhSachCauHoi.Count == 0)
            {
                DanhSachCauHoi.Add(new clsCauHoi());
                Notice.InnerText = "Chưa có câu hỏi nào trong bộ đề.";
                Notice.Visible = true;
                Errors.Visible = false;
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
                gridDanhSachCauHoi.Rows[0].Visible = false;
                Session["DanhSachCauHoi"] = null;
            }
            else
            {
                Notice.Visible = false;
                Errors.Visible = false;
                DemLoaiCauHoi(DanhSachCauHoi,0);
              
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
                Session["DanhSachCauHoi"] = DanhSachCauHoi;
            }
            lnkThemCauHoiVaoDe.Text = "Thêm câu hỏi mới";
        }

        // Ẩn hiện control
        private void KhoaControl(Boolean khoa)
        {
            pXayDungDe.Visible = !khoa;
            pDanhSachDe.Visible = khoa;
        }

        
        protected List<clsChuyenMuc> LoadChuyenMuc()
        {
            ChuyenMucBLL ChuyenMucService = new ChuyenMucBLL();
            List<clsChuyenMuc> DanhSachChuyenMuc = ChuyenMucService.LayDanhSachChuyenMuc();
            DanhSachChuyenMuc.Insert(0, new clsChuyenMuc("--Chọn chuyên mục--", ""));
            _chuyenmuc = DanhSachChuyenMuc;
            return DanhSachChuyenMuc;
        }
        #endregion
        #region Phần lọc
        private int ChekBoLoc()
        {
            int rs = 1;
            if (ddlChuyenMuc.SelectedIndex != 0 && ddlChuyenMuc.SelectedIndex != 1)
                rs++;
            if (ddlKyNang.SelectedIndex != 0 && ddlKyNang.SelectedIndex != 1)
                rs++;
            if (ddlMucDo.SelectedIndex != 0 && ddlMucDo.SelectedIndex != 1)
                rs++;
            if (ddlLoaiCauHoi.SelectedIndex != 0)
                rs++;
            return rs;
        }
        protected void ddlChuyenMuc_SelectedIndexChanged(object sender, EventArgs e)
        {
            TimTheoBoLoc(Convert.ToInt32(ddlChuyenMuc.SelectedValue), "ChuyenMuc");
        }

        protected void ddlKyNang_SelectedIndexChanged(object sender, EventArgs e)
        {
            TimTheoBoLoc(Convert.ToInt32(ddlKyNang.SelectedValue), "KyNang");
        }

        protected void ddlMucDo_SelectedIndexChanged(object sender, EventArgs e)
        {
            TimTheoBoLoc(Convert.ToInt32(ddlMucDo.SelectedValue), "MucDo");
        }

        protected void ddlLoaiCauHoi_SelectedIndexChanged(object sender, EventArgs e)
        {
            TimTheoBoLoc(Convert.ToInt32(ddlLoaiCauHoi.SelectedValue), "LoaiCauHoi");
        }

        private void TimTheoBoLoc(int key, string FilterType)
        {
            try
            {
                CauHoiBLL CauHoiService = new CauHoiBLL();
                DanhSachCauHoi = (Session["DanhSachCauHoi"] as List<clsCauHoi>); ;
                // Chỉ có 1 điều kiện lọc duy nhất và chọn là tất cả
                if (key == 0 && ChekBoLoc() == 1)
                {
                    gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataBind();
                    Session["DanhSachCauHoiTemp"] = null;
                    return;
                }
                // Có từ 2 điều kiện lọc trở lên
                if (ddlChuyenMuc.SelectedIndex != 0 && ddlChuyenMuc.SelectedIndex != 1)
                    DanhSachCauHoi = CauHoiService.LayCauHoiTheoBoLoc(DanhSachCauHoi, Convert.ToInt32(ddlChuyenMuc.SelectedValue), "ChuyenMuc");
                if (ddlKyNang.SelectedIndex != 0 && ddlKyNang.SelectedIndex != 1)
                    DanhSachCauHoi = CauHoiService.LayCauHoiTheoBoLoc(DanhSachCauHoi, Convert.ToInt32(ddlKyNang.SelectedValue), "KyNang");
                if (ddlLoaiCauHoi.SelectedIndex != 0 )
                    DanhSachCauHoi = CauHoiService.LayCauHoiTheoBoLoc(DanhSachCauHoi, Convert.ToInt32(ddlLoaiCauHoi.SelectedValue), "LoaiCauHoi");
                if (ddlMucDo.SelectedIndex != 0 && ddlMucDo.SelectedIndex != 1)
                    DanhSachCauHoi=CauHoiService.LayCauHoiTheoBoLoc(DanhSachCauHoi, Convert.ToInt32(ddlMucDo.SelectedValue), "MucDo");
                if (DanhSachCauHoi.Count == 0)
                {
                    DanhSachCauHoi.Add(new clsCauHoi());
                    Notice.InnerText = "Không tìm thấy câu hỏi nào thỏa điều kiện tìm kiếm của bạn.";
                    Notice.Visible = true;
                    Errors.Visible = false;
                    Session["DanhSachCauHoiTemp"] = null;
                    gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataBind();
                    gridDanhSachCauHoi.Rows[0].Visible = false;
                }
                else
                {
                    Errors.Visible = false;
                    Notice.Visible = false;
                    Session["DanhSachCauHoiTemp"] = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataBind();
                }
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
            }

        }

        #endregion

        protected void lnkBack_Click(object sender, EventArgs e)
        {
            // Hủy Session
            Session["DanhSachCauHoiTemp"] = null;
            Session["Sort"] = null;
            LoadBoDe();
        }
        private void LoadBoDe()
        {
            BoDeBLL BoDeService = new BoDeBLL();
            List<clsBoDe> DanhSachBoDe = BoDeService.DanhSachBoDe();
            if (DanhSachBoDe.Count == 0)
            {
                DanhSachBoDe.Add(new clsBoDe());
                gridDanhSachDe.DataSource = DanhSachBoDe;
                gridDanhSachDe.DataBind();
                gridDanhSachDe.Rows[0].Visible = false;
                Session["DanhSachDe"] = null;
            }
            else
            {
                if (Session["Sort"] != null)
                    DanhSachBoDe.Sort((Session["Sort"] as SoSanh).CompareMethod);
                gridDanhSachDe.DataSource = DanhSachBoDe;
                gridDanhSachDe.DataBind();
                Session["DanhSachDe"] = DanhSachBoDe;
            }
          
            KhoaControl(true);
        }
        // khi chọn vào nút Xây Dựng Đề Trên GridView
        protected void lnkXayDung_Click(object sender, EventArgs e)
        {
            Session["Sort"] = null;
            // Load bộ đề
            BoDeBLL BoDeService = new BoDeBLL();
            ddlBoDe.DataTextField = "TenDe";
            ddlBoDe.DataValueField = "MaDe";
            List<clsBoDe> DanhSachBoDe = BoDeService.DanhSachBoDe();
            DanhSachBoDe.Insert(0, new clsBoDe("--Chọn bộ đề--", 0, ""));
            ddlBoDe.DataSource = DanhSachBoDe;
            ddlBoDe.DataBind();
            int made = Convert.ToInt32((sender as LinkButton).CommandName);
            ddlBoDe.SelectedValue = made.ToString();
            DanhSachCauHoi = BoDeService.LayDanhSachCauHoiThuocBoDe(made,1);
            if (DanhSachCauHoi.Count == 0)
            {
                DanhSachCauHoi.Add(new clsCauHoi());
                Notice.InnerText = "Chưa có câu hỏi nào trong bộ đề.";
                Notice.Visible = true;
                Errors.Visible = false;
                Session["DanhSachCauHoi"] = null;
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
                gridDanhSachCauHoi.Rows[0].Visible = false;
            }
            else
            {
                Notice.Visible = false;
                Errors.Visible = false;
                DemLoaiCauHoi(DanhSachCauHoi,0);
                Session["DanhSachCauHoi"] = DanhSachCauHoi;
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
            }
            KhoaControl(false);
            lnkThemCauHoiVaoDe.Text = "Thêm câu hỏi mới";
        }

        // Hiện thị số câu hỏi theo mức trên màn hình đồng thời cập nhật số câu hỏi và thời gian làm bài
        private void DemLoaiCauHoi(List<clsCauHoi> DanhSachCauHoi, int flag)
        {
            int socaude = 0, socautrungbinh = 0, socaukho = 0;
            int tgcaude = 0, tgcautrungbinh=0, tgcaukho = 0;
            MucDoBLL MucDoService = new MucDoBLL();
            List<clsMucDo> DanhSachMucDo = MucDoService.DanhSachDoKho();
            foreach (clsMucDo mucdo in DanhSachMucDo)
            {
                if (mucdo.MaMucDo == 1)
                    tgcaude = mucdo.ThoiGianThucHien;
                else if (mucdo.MaMucDo == 2)
                    tgcaude = mucdo.ThoiGianThucHien;
                else
                    tgcaukho = mucdo.ThoiGianThucHien;
            }
            int tongthoigian = 0;
            foreach (clsCauHoi cauhoi in DanhSachCauHoi)
            {
                if (cauhoi.MucDo.MaMucDo == 1)
                {
                    socaude++;
                    tongthoigian += tgcaude;
                }
                else if (cauhoi.MucDo.MaMucDo == 2)
                {
                    socautrungbinh++;
                    tongthoigian += tgcautrungbinh;
                }
                else
                {
                    socaukho++;
                    tongthoigian += tgcaukho;
                }
            }
            // Hiện thị
            lblSoCauDe.Text = socaude.ToString();
            lblSoCauTrungBinh.Text = socautrungbinh.ToString();
            lblSoCauKho.Text = socaukho.ToString();
            int tongcauhoi = socaude + socautrungbinh + socaukho;
            lblTongSoCau.Text = tongcauhoi.ToString();
            // Update
            if (flag == 1)
            {
                BoDeBLL BoDeService = new BoDeBLL();
                try
                {
                    BoDeService.CapNhatSoCauHoi_ThoiGian(tongcauhoi, tongthoigian, Convert.ToInt32(ddlBoDe.SelectedValue));
                }
                catch (Exception ex)
                {
                    Errors.InnerText = ex.Message;
                    Errors.Visible = true;
                    Notice.Visible = false;
                }
            }

           
        }
        // Phân trang
        protected void gridDanhSachCauHoi_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridDanhSachCauHoi.PageIndex = e.NewPageIndex;
            if (Session["DanhSachCauHoiTemp"] != null)
                gridDanhSachCauHoi.DataSource = Session["DanhSachCauHoiTemp"] as List<clsCauHoi>;
            else
                gridDanhSachCauHoi.DataSource = Session["DanhSachCauHoi"] as List<clsCauHoi>;
            gridDanhSachCauHoi.DataBind();
            // Nếu hiện tại nó đang ở danh sách câu hỏi không thuộc đề Set lại command khi load trang
            if (lnkThemCauHoiVaoDe.Text != "Thêm câu hỏi mới")
            {
                ImageButton img = (gridDanhSachCauHoi.HeaderRow.FindControl("lnkCommand") as ImageButton);
                img.CommandName = "Them";
                img.ImageUrl = imgInsert.ImageUrl;
                img.ToolTip = "Thêm vào danh sách bộ đề.";
            }
        }

        protected void lnkThemCauHoiVaoDe_Click(object sender, EventArgs e)
        {
            BoDeBLL BoDeService = new BoDeBLL();
            DanhSachCauHoi = new List<clsCauHoi>();
            int flag = 1;
            if (lnkThemCauHoiVaoDe.Text == "Thêm câu hỏi mới")
            {
                hidDanhSachTruoc.Value = "KhongThuoc";
                flag = 0;
                lblTieuDe.Text = "Danh sách câu hỏi không thuộc bộ đề";
                DanhSachCauHoi = BoDeService.LayDanhSachCauHoiKhongThuocBoDe(Convert.ToInt32(ddlBoDe.SelectedValue));
                lnkThemCauHoiVaoDe.Text = "Trở về";
            }
            else
            {
                hidDanhSachTruoc.Value = "ThuocDe";
                lblTieuDe.Text = "Danh sách câu hỏi thuộc bộ đề";
                DanhSachCauHoi = BoDeService.LayDanhSachCauHoiThuocBoDe(Convert.ToInt32(ddlBoDe.SelectedValue),1);
                DemLoaiCauHoi(DanhSachCauHoi,0);
                lnkThemCauHoiVaoDe.Text = "Thêm câu hỏi mới";
            }      
            // Tạo dòng Default nếu danh sách rỗng
            Session["DanhSachCauHoi"] = DanhSachCauHoi;
            Session["DanhSachCauHoiTemp"] = null;
            if (DanhSachCauHoi.Count == 0)
            {
                DanhSachCauHoi.Add(new clsCauHoi());
                Notice.InnerText = "Không có câu hỏi nào.";
                Notice.Visible = true;
                ScriptManager1.SetFocus(Notice);
                Session["DanhSachCauHoi"] = null;
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
                gridDanhSachCauHoi.Rows[0].Visible = false;
            }
            else
            {
                Errors.Visible = false;
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
            }
            if (flag == 0)
            {
                ImageButton img = (gridDanhSachCauHoi.HeaderRow.FindControl("lnkCommand") as ImageButton);
                img.CommandName = "Them";
                img.ImageUrl = imgInsert.ImageUrl;
                img.ToolTip = "Thêm vào danh sách bộ đề.";
            }
            // Nếu cột này đang ẩn do chọn vào danh sách câu hỏi con thì bậc lện
            if(gridDanhSachCauHoi.Columns[0].Visible==false)
            {
                gridDanhSachCauHoi.Columns[0].Visible = true;
            }

        }
        // Thực hiện thêm hoặc xóa một số câu hỏi vào bộ đề
        private void ThucHien(string strCommand)
        {
            try
            {
                int dem = 0;
                ChiTietBoDeBLL ChiTietService = new ChiTietBoDeBLL();
                for (int i = 0; i < gridDanhSachCauHoi.Rows.Count; i++)
                {
                    CheckBox chk = (gridDanhSachCauHoi.Rows[i].FindControl("chkChon") as CheckBox);
                    Boolean val = chk.Checked;
                    if (val == true)
                    {
                        
                        int macauhoi = Convert.ToInt32((gridDanhSachCauHoi.Rows[i].FindControl("lblMaCauHoi") as Label).Text);
                        int made = Convert.ToInt32(ddlBoDe.SelectedValue);
                        clsChiTietBoDe ChiTiet = new clsChiTietBoDe(made, macauhoi);
                        if (strCommand == "Them")
                            ChiTietService.ThemChiTietBoDe(ChiTiet);
                        else
                            ChiTietService.XoaChiTiet(ChiTiet);
                        dem++;
                    }
                }
                
                lblTieuDe.Text = "Danh sách câu hỏi thuộc bộ đề";
                // Chuyển sang danh sách câu hỏi trong đề
                BoDeBLL BoDeService = new BoDeBLL();
                DanhSachCauHoi = BoDeService.LayDanhSachCauHoiThuocBoDe(Convert.ToInt32(ddlBoDe.SelectedValue),1);
                if (dem > 0)
                {
                    DemLoaiCauHoi(DanhSachCauHoi, 1);
                }
                if (DanhSachCauHoi.Count == 0)
                {
                    DanhSachCauHoi.Add(new clsCauHoi());
                    Notice.InnerText = "Chưa có câu hỏi nào trong bộ đề.";
                    Notice.Visible = true;
                    Errors.Visible = false;
                    Session["DanhSachCauHoi"] = null;
                    gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataBind();
                    gridDanhSachCauHoi.Rows[0].Visible = false;
                }
                else
                {
                    if (Session["Sort"] != null)
                        DanhSachCauHoi.Sort((Session["Sort"] as SoSanh).CompareMethod);
                    Errors.Visible = false;
                    Notice.Visible = false;
                    Session["DanhSachCauHoi"] = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                    gridDanhSachCauHoi.DataBind();
                }
         
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
            }
           
        }

        protected void gridDanhSachCauHoi_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Them")
            {
                ThucHien(e.CommandName);
                lnkThemCauHoiVaoDe.Text = "Thêm câu hỏi mới";
            }
            else if (e.CommandName == "Xoa")
            {
                ThucHien(e.CommandName);
            }

        }

        protected void gridDanhSachDe_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                try
                {
                    string tenbode = (gridDanhSachDe.FooterRow.FindControl("txtTenBoDe") as TextBox).Text;
                    int machuyenmuc = Convert.ToInt32((gridDanhSachDe.FooterRow.FindControl("dropChuyenMuc") as DropDownList).SelectedValue);
                    string mota = (gridDanhSachDe.FooterRow.FindControl("txtMoTa") as TextBox).Text;
                    clsBoDe BoDe = new clsBoDe(tenbode, machuyenmuc, mota);
                    BoDeBLL BoDeService = new BoDeBLL();
                    BoDeService.ThemBoDe(BoDe);
                    Notice.Visible = true;
                    ScriptManager1.SetFocus(gridDanhSachDe);
                    Notice.InnerText = "Thêm thành công";
                    Errors.Visible = false;
                    LoadBoDe();
                }
                catch (Exception ex)
                {
                    ScriptManager1.SetFocus(gridDanhSachDe);
                    Errors.InnerText = ex.Message;
                    Errors.Visible = true;
                    Notice.Visible = false;
                }
            }
        }

        protected void gridDanhSachCauHoi_Load(object sender, EventArgs e)
        {
            ScriptManager.RegisterClientScriptBlock(base.Page, this.GetType(), "initalizetooltip", "initalizetooltip()", true);
        }

        protected string GenerateTooltip(int MaCauHoi, string NoiDung, object oDanhSachDapAn)
        {
            if (NoiDung == null)
            {
                return "";
            }
            Regex re = new Regex("<(.|\n)+?>", RegexOptions.IgnoreCase);
            string nd = re.Replace(NoiDung, "");
            if (nd.Length > 30)
                nd = nd.Substring(0, 30) + "....";
            string _strHTML = @"<a rel=CH_" + MaCauHoi + " href='#' class=tooltip>" + nd + @"</a>
            <div id=CH_" + MaCauHoi + @" class=balloonstyle><p>+Câu " + MaCauHoi + ":" + NoiDung + @"</p>";
            if (oDanhSachDapAn != null)
            {
                List<clsDapAn> DanhSachDapAn = (List<clsDapAn>)oDanhSachDapAn;
                if (DanhSachDapAn.Count != 0)
                {
                    int i = 65;
                    string _strHTMLDa = "";
                    foreach (clsDapAn da in DanhSachDapAn)
                    {

                        _strHTMLDa += "<p>";
                        if (da.DapAnDung == 1)
                            _strHTMLDa += "<img src='" + imgSave.ImageUrl.Replace("~/","") + "' style='border:none;'/>";
                        _strHTMLDa += Convert.ToChar(i++).ToString() + ". " + da.NoiDung + @"</p>";
                    }
                    _strHTML += _strHTMLDa;
                }
            }
            else
            {
                _strHTML = _strHTML.Replace("#", "../Administrator.aspx?goto=XayDungBoDe&Command=LayCauHoiCon&ID=" + MaCauHoi+"&ds="+hidDanhSachTruoc.Value);
            }
            return _strHTML;
        }

        protected void gridDanhSachCauHoi_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string macauhoi = (gridDanhSachCauHoi.Rows[e.NewEditIndex].FindControl("lblMaCauHoi") as Label).Text;
            if (macauhoi != "0")
                Response.Redirect("~/Administrator.aspx?goto=SoanCauHoi&ID=" + macauhoi);
        }

        protected void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            Boolean key = (sender as CheckBox).Checked;
            for (int i = 0; i < gridDanhSachCauHoi.Rows.Count; i++)
            {
                (gridDanhSachCauHoi.Rows[i].FindControl("chkChon") as CheckBox).Checked = key;    
            }
        }


        protected void chkAll_De_CheckedChanged(object sender, EventArgs e)
        {
            Boolean key = (sender as CheckBox).Checked;
            for (int i = 0; i < gridDanhSachDe.Rows.Count; i++)
            {
                (gridDanhSachDe.Rows[i].FindControl("chkChon") as CheckBox).Checked = key;
            }
        }

        protected void lnkDeleteAll_Click(object sender, EventArgs e)
        {
            int dem = 0;
            int sodongchon = 0;
            BoDeBLL BoDeService = new BoDeBLL();
            try
            {
                for (int i = 0; i < gridDanhSachDe.Rows.Count; i++)
                {
                    CheckBox chk = (gridDanhSachDe.Rows[i].FindControl("chkChon") as CheckBox);
                    Boolean val = chk.Checked;
                    if (val == true)
                    {
                        sodongchon++;
                        int made = Convert.ToInt32((gridDanhSachDe.Rows[i].FindControl("lblMaBoDe") as Label).Text);
                        int kq = BoDeService.XoaBoDe(made);
                        if (kq == 1)
                            dem++;
                    }
                }
               
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
            }
            finally
            {
                if (sodongchon == 0)
                {
                    Errors.Visible = false;
                    Notice.Visible = true;
                    Notice.InnerHtml = "Chưa chọn dòng cần xóa";
                }
                else
                {
                    Notice.InnerHtml = "Đã xóa " + dem + " bộ đề";
                    Notice.Visible = true;
                    List<clsBoDe> DanhSachDe = BoDeService.DanhSachBoDe();
                    if (Session["Sort"] != null)
                        DanhSachDe.Sort((Session["Sort"] as SoSanh).CompareMethod);
                    Session["DanhSachDe"] = DanhSachDe;
                    ScriptManager1.SetFocus(gridDanhSachDe);
                    gridDanhSachDe.DataSource = DanhSachDe;
                    gridDanhSachDe.DataBind();
                }
                
            }
           
        }

        protected void gridDanhSachDe_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (gridDanhSachDe.Rows.Count <= 1)
            {
                return;
            }
            try
            {
                SoSanh ss;
                if (Session["Sort"] == null)
                {
                    ss = new SoSanh();
                    Session["Sort"] = ss;
                }
                else
                    ss = Session["Sort"] as SoSanh;
                ss.CompareTableNameMethod = SoSanh.TableName.BoDe;
                string sortExpression = e.SortExpression;
                if (sortExpression == "MaBoDe")
                {
                    ss.BoDeCompareTypeMethod = SoSanh.BoDeCompareType.MaBoDe;
                }
                else if (sortExpression == "SoCau")
                {
                    ss.BoDeCompareTypeMethod = SoSanh.BoDeCompareType.SoCau;
                }
                else if (sortExpression == "SoLanThucHien")
                {
                    ss.BoDeCompareTypeMethod = SoSanh.BoDeCompareType.SoLanThucHien;
                }
                else if (sortExpression == "ChuyenMuc")
                {
                    ss.BoDeCompareTypeMethod = SoSanh.BoDeCompareType.ChuyenMuc;
                }
                else if (sortExpression == "TenBoDe")
                {
                    ss.BoDeCompareTypeMethod = SoSanh.BoDeCompareType.TenBoDe;
                }
                else if (sortExpression == "ThoiGian")
                {
                    ss.BoDeCompareTypeMethod = SoSanh.BoDeCompareType.ThoiGian;
                }
                if (ss.TypeSortMethod == SoSanh.TypeSort.Giam)
                    ss.TypeSortMethod = SoSanh.TypeSort.Tang;
                else
                    ss.TypeSortMethod = SoSanh.TypeSort.Giam;
                List<clsBoDe> DanhSachBoDe = new List<clsBoDe>();
                DanhSachBoDe = Session["DanhSachDe"] as List<clsBoDe>;
                DanhSachBoDe.Sort(ss.CompareMethod);
                Session["DanhSachDe"] = DanhSachBoDe;
                gridDanhSachDe.DataSource = DanhSachBoDe;
                gridDanhSachDe.DataBind();
               
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
            }
            
        }

        protected void gridDanhSachCauHoi_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (gridDanhSachCauHoi.Rows.Count <= 1)
            {
                return;
            }
            try
            {
                SoSanh ss;
                if (Session["Sort"] == null)
                {
                    ss = new SoSanh();
                    Session["Sort"] = ss;
                }
                else
                    ss = Session["Sort"] as SoSanh;
                ss.CompareTableNameMethod = SoSanh.TableName.CauHoi;
                string sortExpression = e.SortExpression;
                if (sortExpression == "MaCauHoi")
                {
                    ss.CauHoiCompareTypeMethod = SoSanh.CauHoiCompareType.MaCauHoi;
                }
                else if (sortExpression == "NoiDung")
                {
                    ss.CauHoiCompareTypeMethod = SoSanh.CauHoiCompareType.NoiDung;
                }
                else if (sortExpression == "KyNang")
                {
                    ss.CauHoiCompareTypeMethod = SoSanh.CauHoiCompareType.KyNang;
                }
                else if (sortExpression == "ChuyenMuc")
                {
                    ss.CauHoiCompareTypeMethod = SoSanh.CauHoiCompareType.ChuyenMuc;
                }
                else if (sortExpression == "MucDo")
                {
                    ss.CauHoiCompareTypeMethod = SoSanh.CauHoiCompareType.MucDo;
                }
                if (ss.TypeSortMethod == SoSanh.TypeSort.Giam)
                    ss.TypeSortMethod = SoSanh.TypeSort.Tang;
                else
                    ss.TypeSortMethod = SoSanh.TypeSort.Giam;
                CauHoiBLL CauHoiService = new CauHoiBLL();
                List<clsCauHoi> DanhSachCauHoi = new List<clsCauHoi>();
                if (Session["DanhSachCauHoiTemp"] != null)
                    DanhSachCauHoi = Session["DanhSachCauHoiTemp"] as List<clsCauHoi>;
                else
                    DanhSachCauHoi = Session["DanhSachCauHoi"] as List<clsCauHoi>;
                DanhSachCauHoi.Sort(ss.CompareMethod);
                Session["DanhSachCauHoiTemp"] = DanhSachCauHoi;
                gridDanhSachCauHoi.DataSource = DanhSachCauHoi;
                gridDanhSachCauHoi.DataBind();
                // Nếu hiện tại nó đang ở danh sách câu hỏi không thuộc đề Set lại command khi load trang
                if (lnkThemCauHoiVaoDe.Text != "Thêm câu hỏi mới")
                {
                    ImageButton img = (gridDanhSachCauHoi.HeaderRow.FindControl("lnkCommand") as ImageButton);
                    img.CommandName = "Them";
                    img.ImageUrl = imgInsert.ImageUrl;
                    img.ToolTip = "Thêm vào danh sách bộ đề.";
                }
            }
            catch (Exception ex)
            {
                Errors.InnerText = ex.Message;
                Errors.Visible = true;
                Notice.Visible = false;
            }
           
        }

        protected void gridDanhSachDe_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (Session["Sort"] != null)
                {
                    string kytu = "";
                    SoSanh ss = Session["Sort"] as SoSanh;
                    if (ss.TypeSortMethod == SoSanh.TypeSort.Giam)
                        kytu = "<img src='" + imgDesc.ImageUrl.Replace("~/", "") + "' style='border:none;' />";
                    else
                        kytu = "<img src='" + imgAsc.ImageUrl.Replace("~/", "") + "' style='border:none;' />";
                    int i = SortIndexBoDe(ss.BoDeCompareTypeMethod.ToString());
                    System.Web.UI.WebControls.LinkButton lnk = (LinkButton)e.Row.Cells[i].Controls[0];
                    lnk.Text = gridDanhSachDe.Columns[i].HeaderText + "&nbsp;" + kytu;
                }
                
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                TextBox txtTen = e.Row.FindControl("txtTenBoDe") as TextBox;
                DropDownList drop = e.Row.FindControl("dropChuyenMuc") as DropDownList;
                LinkButton lnk = e.Row.FindControl("lnkInsert") as LinkButton;
                lnk.Attributes.Add("onclick","return Check('"+txtTen.ClientID+"','"+drop.ClientID+"');");
            }

        }

        protected void gridDanhSachCauHoi_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (Session["Sort"] != null)
                {
                    string kytu = "";
                    SoSanh ss = Session["Sort"] as SoSanh;
                    if (ss.TypeSortMethod == SoSanh.TypeSort.Giam)
                        kytu = "<img src='" + imgDesc.ImageUrl.Replace("~/", "") + "' style='border:none;' />";
                    else
                        kytu = "<img src='" + imgAsc.ImageUrl.Replace("~/", "") + "' style='border:none;' />";
                    int i = SortIndexCauHoi(ss.CauHoiCompareTypeMethod.ToString());
                    System.Web.UI.WebControls.LinkButton lnk = (LinkButton)e.Row.Cells[i].Controls[0];
                    lnk.Text = gridDanhSachCauHoi.Columns[i].HeaderText + "&nbsp;" + kytu;
                }
       
            }
          
        }
        private int SortIndexCauHoi(string sortExpression)
        {

            if (sortExpression == "MaCauHoi")
            {
                return 1;
            }
            else if (sortExpression == "NoiDung")
            {
                return 2;
            }
            else if (sortExpression == "KyNang")
            {
                return 4;
            }
            else if (sortExpression == "ChuyenMuc")
            {
                return 5;
            }
            else
            {
                return 3;
            }
        }

        private int SortIndexBoDe(string sortExpression)
        {

            if (sortExpression == "MaBoDe")
            {
                return 1;
            }
            else if (sortExpression == "TenBoDe")
            {
                return 2;
            }
            else if (sortExpression == "SoCau")
            {
                return 4;
            }
            else if (sortExpression == "ThoiGian")
            {
                return 5;
            }
            else if (sortExpression == "SoLanThucHien")
            {
                return 7;
            }
            else 
            {
                return 3;
            }
        }

        protected List<clsChuyenMuc> _chuyenmuc;
        protected int Select(string value)
        {
            foreach (clsChuyenMuc  cm in _chuyenmuc)
            {
                if (cm.TenChuyenMuc == value)
                    return cm.MaChuyenMuc;
            }
            return 0;
        }

        protected void lnkBackCauHoiCon_Click(object sender, EventArgs e)
        {
         
            Session["DanhSachCauHoiTemp"] = null;
            lnkBackCauHoiCon.Visible = false;
            gridDanhSachCauHoi.DataSource = Session["DanhSachCauHoi"] as List<clsCauHoi>;
            gridDanhSachCauHoi.DataBind();
            gridDanhSachCauHoi.Columns[0].Visible = true;
            ImageButton img = (gridDanhSachCauHoi.HeaderRow.FindControl("lnkCommand") as ImageButton);
            if (hidDanhSachTruoc.Value == "ThuocDe")
            {
                lblTieuDe.Text = "Danh sách câu hỏi thuộc bộ đề";
                img.CommandName = "Xoa";
                img.ImageUrl = imgDelete.ImageUrl;
                img.ToolTip = "Xóa khỏi danh sách bộ đề.";
            }
            else
            {
                lblTieuDe.Text = "Danh sách câu hỏi không thuộc bộ đề";
                img.CommandName = "Them";
                img.ImageUrl = imgInsert.ImageUrl;
                img.ToolTip = "Thêm vào danh sách bộ đề.";
            }
        }
    }
}